package com.mgm.controller.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mgm.affiliate.service.AffiliateService;
import com.mgm.affsettings.service.AffsettingsService;
import com.mgm.constant.APICode;
import com.mgm.constant.GobalConstant;
import com.mgm.country.service.CountryService;
import com.mgm.dto.offer.OfferRoot;
import com.mgm.result.IMessage;
import com.mgm.result.offer.OfferResult;

/**
 * 下发给渠道的Offer接口
 * @ClassName: APIController 
 * @Description: 渠道拉取offer的API
 * @author Andy Zhang
 * @date 2018年8月6日 上午10:10:22 
 * 二级域名：api.moboair.net 
 *
 */
@Controller
@RequestMapping("/api")
public class DistributeController {
	
	private static Logger logger =LoggerFactory.getLogger(DistributeController.class);
	
	@Autowired
	private AffiliateService affiliateService;
	@Autowired
	private AffsettingsService affsettingsService;
	@Autowired
	private CountryService countryService;
	
	@RequestMapping(value="/v1/offers", method = RequestMethod.GET)
    public ResponseEntity<OfferResult<List<OfferRoot>>> getOffers(@RequestParam(value="token", required=true) String token,
    		@RequestParam(value="affid", required=true) String affid, @RequestParam(value="platform", required=false) String platform,
    		@RequestParam(value="countries", required=false) String countries,
    		HttpServletRequest request, HttpServletResponse response){
		logger.info("【渠道 {} 拉取Offer：】 from Http URL ： {}", affid, request.getRequestURL() + "?" + request.getQueryString());
		OfferResult<List<OfferRoot>> os = OfferResult.success(new ArrayList<>());
		Map<String,String> pmap = new HashMap<String,String>(); //条件map
		pmap.put("affid", affid); //添加查询条件
		if (!StringUtils.isEmpty(platform)){
			if(!platform.equalsIgnoreCase("ios") && !platform.equalsIgnoreCase("android")) { // 如果平台不为空，只能是ios,android两个值，二选一
				IMessage msg = IMessage.errorCode(APICode.PARAMETER_ERROR.getCode(), APICode.PARAMETER_ERROR.getMessage()); //参数错误
				return new ResponseEntity<OfferResult<List<OfferRoot>>>(os.error(msg), HttpStatus.OK);
			} else {
				pmap.put("platform", platform.toLowerCase()); //转小写
			}
		}
			
		if(!StringUtils.isEmpty(countries)) {
			String[] abbrs = countries.split(",");
			if (!countryService.selectByAbbr(abbrs).isSuccess()) { //country参数出错 (数据库没有该Country)
				IMessage msg = IMessage.errorCode(APICode.PARAMETER_ERROR.getCode(), APICode.PARAMETER_ERROR.getMessage()); //参数错误
				return new ResponseEntity<OfferResult<List<OfferRoot>>>(os.error(msg), HttpStatus.OK);
			} else {
				String str = "(";
				for (int i = 0; i < abbrs.length; i++) {
					str += "locate('"+abbrs[i]+"', countries)" ;
					if(i<abbrs.length-1) {
						str += " or ";
					}
				}
				str += ")";
				pmap.put("countries", str); 
			}
		}
		
		
		if(!affiliateService.findByAffId(affid, token).isSuccess()) { //affid & token 查询失败
			IMessage msg = IMessage.errorCode(APICode.PARAMETER_MISMATCH.getCode(), APICode.PARAMETER_MISMATCH.getMessage()); //token and affid do not match
			return new ResponseEntity<OfferResult<List<OfferRoot>>>(os.error(msg), HttpStatus.OK);
		}
		
		List<OfferRoot> list = replaceVal(affsettingsService.getAffOffer(pmap), pmap.get("affid"));
		OfferResult<List<OfferRoot>> res = OfferResult.success(list);
		logger.info("【下发的Offer：】  共 {} 条", CollectionUtils.isEmpty(list) ? 0 : list.size());
		return new ResponseEntity<OfferResult<List<OfferRoot>>>(res, HttpStatus.OK);
    }
	
	private List<OfferRoot> replaceVal(List<OfferRoot> list, String affid){
		if(CollectionUtils.isEmpty(list)) {
			return null;
		}
		//https://moboair.net/v1/click?offid=1532419819724&affid=aff3514&tid={transaction_id}&pkgname={pkgname}&subaffid={subaffid}&idfa={idfa}&gaid={gaid}&aid={aid}&data1={data1}&data2={data2}&data3={data3}&data4={data4}
		for (OfferRoot offerRoot : list) {
			offerRoot.setClick_url(GobalConstant.HOST_NAME + "?offid="
					+ offerRoot.getOfferid() + "&affid=" + affid
					+ "&tid={transaction_id}&pkgname={pkgname}&subaffid={subaffid}&idfa={idfa}&gaid={gaid}&aid={aid}"
					+ "&data1={data1}&data2={data2}&data3={data3}&data4={data4}");
		}
		return list;
	}
	
	@RequestMapping(value = "test", method = RequestMethod.GET)
	public String testOffer() {
		return "ok";
	}
}
